#include <iostream>
#include <sstream>
#include <stdio.h>

#include <OpenXLSX.hpp>
#include <nowide/cstdio.hpp>

using namespace std;
using namespace OpenXLSX;

const int E_EXCEPTION = -1;
const int E_SUCC = 0;
const int E_PARAM_NUM = 1;
const int E_OUT_FILE = 2;

int main(int argc, char **argv)
{
	if (argc != 3)
		return E_PARAM_NUM;

	try {
		const char* infile = argv[1];
		const char* outfile = argv[2];
		XLDocument doc;
		doc.open(infile);
		vector<string>& names = doc.workbook().sheetNames();

		FILE* file = nowide::fopen(outfile, "w");
		if (file == NULL) {
			doc.close();
			return E_OUT_FILE;
		}
		ostringstream out;

		out << "return {\n";

		for each (auto n in names) {
			auto wks = doc.workbook().worksheet(n);

			out << "[\"" << n << "\"] = {\n"; // new table for sheet begin

			for (auto& row : wks.rows()) {
				ostringstream o;
				o << "  " << "{";
				for (auto& value : std::vector<XLCellValue>(row.values())) {
					switch (value.type()) {
					case XLValueType::Boolean:
						o << (value ? "true" : "false") << ",";
						break;
					case XLValueType::Integer:
					case XLValueType::Float:
						o << value << ",";
						break;
					case XLValueType::String:
						o << "\"" << value << "\",";
						break;
					case XLValueType::Empty:
						o << "nil,";
						break;
					}
				}
				auto s = o.str();
				auto e = std::remove(s.begin(), s.end(), '\r');
				s.erase(e, s.end());
				e = std::remove(s.begin(), s.end(), '\n');
				s.erase(e, s.end());
				out << s.c_str() << "},\n";
			}

			out << "},\n"; // new table for sheet end
		}

		out << "}";
		fprintf(file, "%s\n", out.str().c_str());

		doc.close();
		fclose(file);
	}
	catch (const std::exception& e)
	{
		cout << "exception: " << e.what() << endl;
		return E_EXCEPTION;
	}
	return E_SUCC;
}
